﻿using Services.Equ.PcapCommunication.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.Equ.PcapCommunication.Operation
{
    public class UpgradeOperation:PcapOperation<bool>
    {
        public UpgradeOperation(IEnumerable<AbstractPcapCommunication<bool>> pcapCommunications):base(pcapCommunications) 
        { 

        }
        public override async Task<Dictionary<int, List<bool>>?> GetOperationResult()
        {
            SetUUID();
            bool result = await IsExecSuccess(ConnetCommunication, ReleaseCommunication);
            if(result)
            {
                int i = 0;
                var pre = ConnetCommunication;
                Dictionary<int, List<bool>> dic = new Dictionary<int, List<bool>>();
                foreach(var communication in PcapCommunications)
                {
                    communication.SeqId= pre.SeqId+1;
                    pre = communication;
                    result = await IsExecSuccess(communication);
                    dic.Add(i, [result]);
                    if (!result)
                    {
                        break;
                    }
                    i++;
                }
                ReleaseCommunication.SeqId = pre.SeqId + 1;
                await ReleaseCommunication.GetCommunicationResult();
                return dic;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 执行通讯命令 并返回是否成功
        /// </summary>
        /// <param name="communication"></param>
        /// <param name="failCommunication"></param>
        /// <returns></returns>
        private async Task<bool> IsExecSuccess(AbstractPcapCommunication<bool> communication, AbstractPcapCommunication<bool>? failCommunication = null)
        {
            int r = 0;
            bool isSuccess = false;
            while (!isSuccess && r < ReConnetTimes)
            {
                int preSeqId = communication.SeqId;
                List<bool>? result = await communication.GetCommunicationResult();
                if (result.Any(t => t == true))
                {
                    isSuccess = true;
                }
                else
                {
                    r++;
                    communication.SeqId = preSeqId;
                    if (failCommunication != null)
                    {
                        await failCommunication.GetCommunicationResult();
                    }
                }
            }
            return isSuccess;
        }
    }
}
